<template>
  <el-dialog :model-value="visible" @update:modelValue="$emit('update:visible', $event)"
    :title="form.reservationId ? '📋 修改预约信息' : '🌾 填写预约信息'" width="720px" :close-on-click-modal="false"
    class="appointment-dialog">
    <div class="form-wrapper" :style="{ opacity: loading ? 0.6 : 1, pointerEvents: loading ? 'none' : 'auto' }">

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left"
        class="form-content">

        <!-- 编辑模式显示医生选择框 -->
        <el-form-item label="选择医生" prop="doctorId" v-if="form.reservationId">
          <el-select v-model="form.doctorId" placeholder="预约医生" style="width: 100%" @change="handleDoctorChange">
            <el-option v-for="doc in doctors" :key="doc.doctorId" :label="doc.doctorName" :value="doc.doctorId" />
          </el-select>
        </el-form-item>


        <!-- 新增模式显示医生信息 -->
        <div v-else class="doctor-info">预约医生：{{ doctor?.doctorName || '未知医生' }}</div>


        <el-form-item label="预约日期" prop="reservationDate">
          <el-date-picker v-model="form.reservationDate" type="date" placeholder="请选择预约日期" :disabled-date="disabledDate"
            style="width: 100%" @change="onDateChange" :disabled="loading" />
        </el-form-item>

        <el-form-item label="预约时间" prop="reservationTime">
          <el-select v-model="form.reservationTime" placeholder="请选择时间段" style="width: 100%; height: 44px"
            :disabled="loading || loadingTimes">
            <el-option v-for="time in availableTimes" :key="time" :label="`${time} ~ ${formatEndTime(time)}`"
              :value="time" />
          </el-select>
          <div class="form-tips">
            每天可预约时间段（09:00~12:00，13:00~18:00），其中 12:00~13:00 为休息时间
          </div>
        </el-form-item>

        <el-form-item label="宠物名字" prop="petName">
          <el-input v-model="form.petName" placeholder="请输入宠物昵称（2-10个字符）" :disabled="loading" />
        </el-form-item>

        <el-form-item label="宠物品种" prop="petType">
          <el-select v-model="form.petType" placeholder="请选择宠物品种" style="width: 100%; height: 44px" :disabled="loading">
            <el-option label="犬类" value="犬类" />
            <el-option label="猫科" value="猫科" />
            <el-option label="鼠类" value="鼠类" />
            <el-option label="鸟类" value="鸟类" />
            <el-option label="鱼类" value="鱼类" />
          </el-select>
        </el-form-item>

        <el-form-item label="主人姓名" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入您的真实姓名" :disabled="loading" />
        </el-form-item>

        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入11位手机号码" maxlength="11" :disabled="loading" />
        </el-form-item>

        <el-form-item label="症状描述(选填)" prop="remark">
          <el-input type="textarea" v-model="form.remark" :rows="6" placeholder="请详细描述宠物症状" resize="none"
            maxlength="200" :disabled="loading" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="footer-actions">
        <el-button @click="handleCancel" :disabled="loading">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ form.reservationId ? '保存修改' : '确认预约' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addAppointment, fetchAvailableTimes, getDoctorList, updateAppointment } from '@/api/appointment'
import dayjs from 'dayjs'

const props = defineProps({
  visible: Boolean,
  doctor: Object,
  formData: Object,
  doctors: Array
})

const emit = defineEmits(['update:visible', 'updated'])

const formRef = ref()
const loading = ref(false)
const loadingTimes = ref(false)
const availableTimes = ref()
const doctors = ref()

const form = ref({
  reservationId: '',
  doctorId: '',
  reservationDate: null,
  reservationTime: '',
  petName: '',
  petType: '',
  nickname: '',
  phone: '',
  remark: ''
})



const rules = {
  doctorId: [{
    required: !!form.value.reservationId,
    message: '请选择医生',
    trigger: 'change'
  }],
  reservationDate: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
  reservationTime: [{ required: true, message: '请选择预约时间段', trigger: 'change' }],
  petName: [
    { required: true, message: '请输入宠物名字', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符' }
  ],
  petType: [{ required: true, message: '请选择宠物品种', trigger: 'change' }],
  nickname: [{ required: true, message: '请输入主人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
}

const disabledDate = (time: Date) => {
  const today = new Date()
  const max = new Date()
  max.setDate(today.getDate() + 7)
  return time.getTime() < today.setHours(0, 0, 0, 0) || time.getTime() > max.getTime()
}

const handleDoctorChange = () => {
  form.value.reservationTime = ''
  if (form.value.reservationDate) {
    onDateChange()
  }
}

const onDateChange = async () => {
  const dateStr = dayjs(form.value.reservationDate).format('YYYY-MM-DD')
  const doctorId = form.value.reservationId
    ? form.value.doctorId
    : props.doctor?.doctorId

  if (!dateStr || !doctorId) return

  loadingTimes.value = true
  try {
    const res = await fetchAvailableTimes(dateStr, doctorId)
    let times = res.code === 200 ? res.data : []

    // 如果当前选中的时间不在接口返回的时间列表里，强行加入（用于编辑模式回显）
    if (
      form.value.reservationTime &&
      !times.includes(form.value.reservationTime)
    ) {
      times = [form.value.reservationTime, ...times]
    }

    availableTimes.value = times
  } catch {
    availableTimes.value = []
  } finally {
    loadingTimes.value = false
  }
}


const formatEndTime = (start: string) => {
  const [h, m] = start.split(':').map(Number)
  return `${h + 1}:${m.toString().padStart(2, '0')}`
}

const handleCancel = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

const resetForm = async () => {
  if (props.formData?.reservationId) {
    const data = props.formData
    form.value = {
      reservationId: data.reservationId,
      doctorId: data.doctorId || '',
      reservationDate: dayjs(data.reservationDate).toDate(),
      reservationTime: data.reservationTime,
      petName: data.petName,
      petType: data.petType,
      nickname: data.nickname,
      phone: data.phone,
      remark: data.remark
    }
    await onDateChange()
  } else {
    form.value = {
      reservationId: '',
      doctorId: props.doctor?.doctorId || '',
      reservationDate: null,
      reservationTime: '',
      petName: '',
      petType: '',
      nickname: '',
      phone: '',
      remark: ''
    }
    availableTimes.value = []
  }
}

const submitForm = () => {
  formRef.value?.validate().then(() => {
    loading.value = true
    const payload = {
      ...form.value,
      doctorId: form.value.reservationId
        ? form.value.doctorId
        : props.doctor?.doctorId,
      reservationDate: dayjs(form.value.reservationDate).format('YYYY-MM-DD')
    }

    const apiMethod = form.value.reservationId ? updateAppointment : addAppointment

    apiMethod(payload)
      .then(() => {
        ElMessage.success(form.value.reservationId ? '修改成功' : '预约成功')
        handleCancel()
        emit('updated')
      })
      .finally(() => {
        loading.value = false
      })

    console.log('payload', payload);

  })
}

watch(() => props.visible, async (val) => {
  if (val) {
    try {
      const res = await getDoctorList()
      doctors.value = res.data || []
      resetForm()
    } catch {
      ElMessage.error('获取医生列表失败')
    }
  }
})
</script>

<style scoped>
.form-wrapper {
  padding: 10px 20px;
  transition: opacity 0.3s ease;
}

.doctor-info {
  font-weight: bold;
  font-size: 15px;
  margin-bottom: 16px;
  color: #409EFF;
}

.form-content .el-form-item {
  margin-bottom: 18px;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 6px;
  line-height: 1.4;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner),
:deep(.el-date-editor),
:deep(.el-select .el-input__inner) {
  height: 44px;
  font-size: 15px;
  line-height: 1.5;
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  min-height: 140px !important;
  resize: none;
}

.footer-actions .el-button {
  padding: 10px 24px;
  border-radius: 6px;
  min-width: 100px;
}

.custom-style .el-segmented {
  --el-segmented-item-selected-color: var(--el-text-color-primary);
  --el-segmented-item-selected-bg-color: #409EFF;
  --el-border-radius-base: 16px;
}
</style>
